package cn.com.yusys.yusp.custManager.service;

import cn.com.yusys.yusp.admin.Utils.IDUtils;
import cn.com.yusys.yusp.admin.domain.RoleLevelProperties;
import cn.com.yusys.yusp.commons.mapper.CommonMapper;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import cn.com.yusys.yusp.commons.service.CommonService;
import cn.com.yusys.yusp.custManager.domain.MarketCustGroup;
import cn.com.yusys.yusp.custManager.domain.WcrmMarketCustGroupRel;
import cn.com.yusys.yusp.custManager.repository.mapper.MarketCustGroupMapper;
import cn.com.yusys.yusp.uaa.security.AuthUtils;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: zoie
 * @Description: 营销客群
 * @Date: 2021/6/17
 * @Version: 1.0
 */
@Service
public class MarketCustGroupService extends CommonService {
    private static final Logger logger = LoggerFactory.getLogger(MarketCustGroupService.class);

    @Autowired
    private MarketCustGroupMapper marketCustGroupMapper;
    @Autowired
    private FlexibleQueryService flexibleQueryService;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    protected CommonMapper getMapper() {
        return this.marketCustGroupMapper;
    }

    /**
     * 查询客户群列表
     * 支行查询一级网格
     * 客户经理查询二级网格
     *
     * @param
     * @return
     */
    public List<Map<String, Object>> getGroupList(QueryModel queryModel) {
        // 设置分页查询参数(设置到线程变量中了)
        PageHelper.startPage(queryModel.getPage(), queryModel.getSize());
        String roleCode = queryModel.getCondition().get("roleCode").toString();
        List<Map<String, Object>> groupInfo = null;
        if(RoleLevelProperties.ROLELEVEL1.contains(roleCode)){
            groupInfo = marketCustGroupMapper.getLevelGridGroup(queryModel);
        }else if(RoleLevelProperties.ROLELEVEL2.contains(roleCode)){
            groupInfo = marketCustGroupMapper.getLevel1GridGroup(queryModel);
        }else if(RoleLevelProperties.ROLELEVEL3.contains(roleCode)){
            groupInfo = marketCustGroupMapper.getLevel2GridGroup(queryModel);
        }
        PageHelper.clearPage();
        return groupInfo;
    }

    /**
     * 更新客户群信息
     *
     * @param marketCustGroup
     * @return
     */
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    public MarketCustGroup saveGroup(MarketCustGroup marketCustGroup) {
        Map parsedTokenMap = AuthUtils.getParsedAccessTokenMap();
        String loginCode = AuthUtils.getCurrentUserLogin(parsedTokenMap);
        marketCustGroup.setLastUpdateUser(loginCode);
        marketCustGroup.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));
        this.updateSelective(getMapper(), marketCustGroup);
        return marketCustGroup;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return int
     */
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    public int batchDeleteGroup(String ids) {
        String[] idList = ids.split(",");
        marketCustGroupMapper.deleteGroups(idList);
        return idList.length;
    }

    /**
     * 根据当前用户（支行）查询所属网格
     *
     * @param orgId
     * @return
     */
    public String getGridIdByOrgId(String orgId) {
        String gridId = marketCustGroupMapper.getGridIdByOrgId(orgId);
        return gridId;
    }

    /**
     * 根据当前用户查询所属网格
     *
     * @param userId
     * @return
     */
    public List<String> getGridIdByUserId(String userId) {
        List<String> gridIds = marketCustGroupMapper.getGridIdByUserId(userId);
        return gridIds;
    }

    /**
     * 灵活查询时创建客户群并且添加客户和客群关系
     * 一级根据机构查询网格编号（唯一），二级根据userId查询多个网格编号
     *
     * @param t
     * @return
     */
//    @Async("taskExecutor")
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    public void insertCusGroup(Map<?, ?> t) {
        String flag = t.get("flag").toString();
        List<Map<String, Object>> cusInfoList;
        //查询所有客户
        if ("1".equals(flag)) {
            String querysql = t.get("querysql").toString();
            cusInfoList = marketCustGroupMapper.selectAllCus(querysql);
        } else {
            // 客户信息
            cusInfoList = (List<Map<String, Object>>) t.get("custGroupPre");
        }
        //根据机构查询网格Id
        String orgId = t.get("orgId").toString();
        String userId = t.get("userId").toString();
        String userName = t.get("userName").toString();
        String roleId = t.get("roleId").toString();
        String gridId="";
        if(RoleLevelProperties.ROLELEVEL2.contains(roleId)){
            gridId=getGridIdByOrgId(orgId);
//            gridIds.add(gridIdByOrgId);
//            // 将list根据gridId字段分类后每个元素值的个数
//            gridIdMap = cusInfoList.stream().collect(
//                    Collectors.groupingBy(doc -> doc.get("gridId"), Collectors.counting()));
        }
        String cusGroupNo = IDUtils.getGuid();
        Map<String, String> cusGroupInfo = (Map<String, String>) t.get("custGroupInfo");
        //客户群组
        String custGroupName = cusGroupInfo.get("custGroupName");
        String custGroupStatus = cusGroupInfo.get("custGroupStatus");
        MarketCustGroup cusGroup = new MarketCustGroup();
        cusGroup.setCustGroupName(custGroupName);
        cusGroup.setCustGroupStatus(custGroupStatus);
        cusGroup.setCustGroupNo(cusGroupNo);
        cusGroup.setCreateUser(userId);
        cusGroup.setCreateUserName(userName);
        cusGroup.setCreateTime(new Timestamp(System.currentTimeMillis()));
        cusGroup.setCustGroupType("1");
        cusGroup.setId(IDUtils.getGuid());
        cusGroup.setGridId(gridId);
        cusGroup.setCustGroupNum(new BigDecimal(cusInfoList.size()));
        marketCustGroupMapper.insertGroup(cusGroup);
//        insertGroups(cusInfoList.size(),gridIdMap, gridIds, cusGroupInfo, cusGroupNo, userId);
        List<WcrmMarketCustGroupRel> list = new ArrayList<>();
        for (Map map : cusInfoList) {
            WcrmMarketCustGroupRel cusGroupRel = new WcrmMarketCustGroupRel();
            cusGroupRel.setCustNo(map.get("custIdBase")!=null?map.get("custIdBase").toString():"");
            cusGroupRel.setCustName(map.get("custNameBase")!=null?map.get("custNameBase").toString():"");
            cusGroupRel.setCustGroupNo(cusGroupNo);
            cusGroupRel.setGridId(map.get("gridId")!=null?map.get("gridId").toString():"");
            cusGroupRel.setSecondGridId(map.get("secondGridId")!=null?map.get("secondGridId").toString():"");
            cusGroupRel.setUserNo(map.get("userNo")!=null?map.get("userNo").toString():"");
            list.add(cusGroupRel);
        }
        insertBatch(list);
    }


    /**
     * 批量插入
     * ExecutorType.BATCH
     *
     * @param list
     */
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    public void insertBatch(List<WcrmMarketCustGroupRel> list) {
        StopWatch watch = new StopWatch();
        watch.start();
//        Long startTime = System.currentTimeMillis();
        // 步骤1 获取线程批量session
        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        // 步骤2 获取mapper
        MarketCustGroupMapper cusGroupMapper = session.getMapper(MarketCustGroupMapper.class);
        // 注意，事务内不允许做查询操作，否则无法做事务回滚，因为查询操作会执行flushStatements
        try {
            list.forEach(demo -> {
                cusGroupMapper.insertCusGroupRel(demo);
            });
            // 步骤3 推送更新
            session.flushStatements();
            watch.stop();
            logger.info("批量插入成功,{}", watch.shortSummary());
        } catch (Exception e) {
            logger.error("逻辑系统初始化失败，错误信息:{}", e.getMessage());
            throw e;
        }
    }

    public int deleteGroup(String id,String custGroupNo) {
        int i = 0;
        int groupCount = marketCustGroupMapper.selectGroupNoCount(custGroupNo);
        if(groupCount==1){//客户群组超过一条说明已下发营销任务
            i = marketCustGroupMapper.deleteByIds(id);
        }
        return i;
    }

    /**
     * 客户明细
     * @param queryModel
     * @return
     */
    public List<Map<String, Object>> getCustInfo(QueryModel queryModel) {
        PageHelper.startPage(queryModel.getPage(), queryModel.getSize());
        String roleCode = queryModel.getCondition().get("roleCode").toString();
        int checkLevel = 0;
        if(RoleLevelProperties.ROLELEVEL1.contains(roleCode)){
            checkLevel = 1;
        }else if(RoleLevelProperties.ROLELEVEL2.contains(roleCode)){
            checkLevel = 2;
        }else if(RoleLevelProperties.ROLELEVEL3.contains(roleCode)){
            checkLevel = 3;
        }
        queryModel.getCondition().put("checkLevel", checkLevel);
        List<Map<String, Object>> list = marketCustGroupMapper.getCustInfo(queryModel);
        PageHelper.clearPage();
        return list;
    }
}


